import useMappingProps from 't/common/hooks/useMappingProps';

import { computed, defineComponent, reactive, ref, watch } from 'vue';

import History from './history';
import ResultList from './resultList';
import Empty from './empty';
// import NoDataPlaceholder from 't/bussiness/data-grid/components/no-data-placeholder.vue';
import NoDataPlaceholder from './empty2';
import Loading from './loading';

import { ItemTemplateGeneralType } from '../interface';
import Style from './main.module.scss';
import './main.scss';

import { useQuasar, debounce } from '@teld/q-components';

import QInput from '@teld/q-components/Input';

import TDialog from 't/basic/dialog';
import TCard from 't/basic/card';
import TCardSection from 't/basic/card/CardSection';
import TIcon from 't/basic/icon';
import TPullToRefresh from 't/basic/pull-to-refresh';
import TInfiniteScroll from 't/basic/infinite-scroll';
import TResizeObserver from 't/basic/resize-observer';
import TButton from 't/basic/button';
import { SpinnerDots as TSpinnerDots } from 't/basic/spinner';



type InfiniteScrollType = {
  resume: () => void;
  stop: () => void;
  updateScrollTarget: () => void;
};

export default defineComponent({
  props: {
    autoQuery: { type: Boolean, default: false },
    itemTemplate: {
      type: String,
      default: 'general',
    },
    itemTemplateCustom: {
      type: Boolean,
      default: false,
    },
    itemTemplateCustomSlot: {
      type: String,
      default: 'default',
    },
    showSearchBar: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '',
    },
    history: {
      type: Boolean,
      default() {
        return true;
      },
    },
    maxCount: {
      type: Number,
      default() {
        return 5;
      },
    },
    itemTemplateGeneral: {
      type: Array<ItemTemplateGeneralType>,
      default: () => [
        {
          type: 'title',
          valueType: '',
          field: '',
          expression: '',
          ellipsis: true,
          demo: '',
        },
        {
          type: 'thumb',
          valueType: '',
          field: '',
          expression: '',
          ellipsis: false,
          demo: '',
        },
        {
          type: 'info',
          valueType: '',
          field: '',
          expression: '',
          ellipsis: true,
          demo: '',
        },
        {
          type: 'info',
          valueType: '',
          field: '',
          expression: '',
          ellipsis: true,
          demo: '',
        },
      ],
    },

    rows: {
      type: Array,
      default: () => [],
    },

    disabled: {
      type: Boolean,
      default: false,
    },
    pullRefresh: {
      type: Boolean,
      default: false,
    },
    error: {
      type: Boolean,
      default() {
        return false;
      },
    },
    loading: {
      type: Boolean,
      default: false,
    },
    finished: {
      type: Boolean,
      default: false,
    },
    refreshing: {
      type: Boolean,
      default: false,
    },
    loadingText: String,
    finishedText: String,
    errorText: {
      type: String,
      default() {
        return '加载失败';
      },
    },
    pullingText: String,
    loosingText: String,
    successText: String,
    histories: {
      type: Array,
      default: () => [],
    },
    totalCount: {
      type: Number,
      default: () => 0,
    },
    showSearchBtn: {
      type: Boolean,
      default: () => false,
    },
    compact: {
      type: Boolean,
      default() {
        return true;
      },
    },
    pageID:{
      type: String,
      default: () => "",
    },
    instanceCode:{
      type: String,
      default: () => "",
    },
    profileKey:{
      type: String,
      default: () => "profileKey",
    },
  },
  emits: [
    'search',
    'clickItem',
    'refresh',
    'load',
    'update:refreshing',
    'clear',
    'updateHistory',
  ],

  setup(props, { attrs, emit, expose, slots }) {
    const $q = useQuasar();
    const inDesign = !!window['fas']?.inDesign;
    const listRef = ref();
    const publicMethod = {
      refresh: () => {
        refreshing.value = true;
        onHandlerRefresh();
      },
      check: () => {
        listRef.value.check();
      },
      open: () => {
        setShowPopup(true);
      },
      close: () => {
        setShowPopup(false);
      },
      searchValue: computed(() => {
        return searchValue.value;
      }),
    };

    const refInfiniteScroll = ref<InfiniteScrollType>();
    const refScrollTargetId = ref(null);
    const refSearch = ref(null);

    const [mappingProps, mappingExpose] = useMappingProps(props, publicMethod);

    expose(mappingExpose);

    const onHandlerSearch = (addHistoryFlag = false) => {
      // refInfiniteScroll.value?.reset();
      // updateScrollTarget()
      refInfiniteScroll.value?.resume();
      refreshing.value = true;
      if (addHistoryFlag) addHistory(searchValue.value);
      onHandlerRefresh();
    };

    const isQueryFlag = ref(false);

    const emitRefreshDebounce = debounce(() => {
      console.log('emitRefreshDebounce');
      emit('refresh', searchValue.value);
    }, 300);

    const onHandlerRefresh = () => {
      isQueryFlag.value = true;
      isHistoryView.value = false;
      console.log('emitRefreshDebounce.onHandlerRefresh');
      emitRefreshDebounce();
    };

    function onHandlerLoad() {
      if (mappingProps.loading) return;
      isQueryFlag.value = true;
      emit('load', searchValue.value);
    }

    const refreshing = computed({
      get() {
        return props.refreshing;
      },
      set(val) {
        emit('update:refreshing', val);
      },
    });

    const renderSearchIcon = () => {
      return (
        <TIcon
          name='icon-fassearch01' style="font-size:16px;"
          onClick={() => !inDesign && setShowPopup(true)}
        />
      );
    };

    const showPopup = ref(false);
    const setShowPopup = state => {
      showPopup.value = state;
      if (state && mappingProps.autoQuery) {
        setTimeout(() => {
          publicMethod.refresh();
        }, 500);
      }
    };

    const renderSearch = () => {
      return (
        <div class='popup-search_container'>
          <QInput
            class='popup-search_searchbar'
            // bg-color='#F0F2F5'
            // dense
            // filled
            standout
            borderless
            outlined={false}
            bottom-slots
            placeholder={mappingProps.placeholder}
            onClick={() => !inDesign && setShowPopup(true)}
            readonly
            // onFocus={(evt)=> {evt.target.blur(); evt.stopPropagation()} }
          >
            {{
              prepend: () => <TIcon name='icon-fassearch01' />,
            }}
          </QInput>
        </div>
      );
    };

    const profileKeys= {
      Key: "FASPopupSearchComp",
      DynamicKey: `History_${props.instanceCode}_${props.profileKey}`,
    };
    let historyArray = reactive(mappingProps.histories);

    const getPageUserProfile=async ()=>{
      let res = []
      try {
        res = window.Funcs
          ? await Funcs.GetPageUserProfile({
              profileKeys,
              PageID: props.pageID,
            })
          : [];
        } catch (error) { }
      return res;
    }

    const setPageProfile = Profile => {
      return Funcs.SetPageUserProfile({
        profileKey:profileKeys,
        PageID: props.pageID,
        profileValue: JSON.stringify(Profile),
      });
    };

    if(props.pageID){
      debugger
      getPageUserProfile().then(res =>{
        let ConfigValue = res?.data && res.data[0] && res.data[0].ConfigValue;
        if(ConfigValue){
          historyArray = reactive(JSON.parse(ConfigValue))
        }
      })

      // watch(()=>historyArray,(histories)=>{
      //   window.Funcs && setPageProfile(histories)
      // })
    }

    const addHistory = item => {
      if (!item) {
        return;
      }
      if (historyArray) {
        const titles = historyArray.map(item => item.title);
        if (titles.includes(item)) {
          return;
        }
      }

      let maxCount = 10;
      if (mappingProps.maxCount != 0) {
        maxCount = mappingProps.maxCount;
      }
      if (historyArray.length >= maxCount) {
        historyArray.pop();
      }
      historyArray.unshift({ title: item });
      emitUpdateHistory(historyArray);
    };

    const emitUpdateHistory = (historyArray)=>{
      if(props.pageID){
        try {
          setPageProfile(historyArray)
        } catch (error) {
          console.log('setPageProfile', error);
          emit('updateHistory', historyArray);
        }
      }else{
        emit('updateHistory', historyArray);
      };
    }

    const onHandlerClickItem = (item, index) => {
      addHistory(searchValue.value);
      emit('clickItem', item, index);
    };

    const searchValue = ref('');
    const searchValueHighlight = ref('');

    watch(
      () => props.totalCount,
      () => {
        searchValueHighlight.value = searchValue.value;
      },
    );


    watch(
      () => showPopup.value,
      val => {
        searchValue.value = '';
        isHistoryView.value = mappingProps.history;
        if (false === val) {
          emit('clear');
          isQueryFlag.value = false;
        } else {
          setTimeout(() => {
            refSearch?.value?.focus();
          });
        }
      },
    );

    watch(
      () => mappingProps.loading,
      () => {
        if (doneCallback.onLoad) {
          doneCallback.onLoad();
          doneCallback.onLoad = null;
        }
      },
    );
    watch(
      () => mappingProps.refresh,
      () => {
        if (doneCallback.refresh) {
          doneCallback.refresh();
          doneCallback.refresh = null;
        }
      },
    );

    watch(
      () => mappingProps.finished,
      val => {
        if (val) refInfiniteScroll.value?.stop();
      },
    );

    watch(
      () => mappingProps.error,
      val => {
        if (doneCallback.onLoad) {
          doneCallback.onLoad();
          doneCallback.onLoad = null;
        }
        if (doneCallback.refresh) {
          doneCallback.refresh();
          doneCallback.refresh = null;
        }
      },
    );

    if (inDesign) {
      watch(
        () => props.itemTemplate,
        val => {
          mappingProps.itemTemplateCustom = 'custom' == val;
        },
      );
    }

    const computedRows = computed(() => {
      return mappingProps.rows;
    });

    const doneCallback: { refresh: any; onLoad: any } = {
      refresh: null,
      onLoad: null,
    };

    const isHistoryView = ref(mappingProps.history);

    const refresh = done => {
      console.log('refresh');
      refreshing.value = true;
      doneCallback.refresh = done;
      onHandlerRefresh();
    };

    const onLoad = (index, done) => {
      if (mappingProps.disabled) {
        done();
      } else {
        doneCallback.onLoad = done;
        onHandlerLoad();
      }
    };

    const readerBottomLine = () => {
      return (
        mappingProps.finished && (
          <div class='t-popup-search-result-item'>
            <div
              class='t-popup-search-result-item__header'
              style={{ justifyContent: 'center' }}
            >
              {$q.lang?.popupSearch?.bottomLineText || '没有更多了'}
            </div>
          </div>
        )
      );
    };

    const readerResultList = () => {
      return (
        <ResultList
          itemTemplateGeneral={props.itemTemplateGeneral}
          list={computedRows.value}
          searchValue={searchValueHighlight.value}
          onClickItem={onHandlerClickItem}
        >
          {readerBottomLine()}
        </ResultList>
      );
      // return computedRows.value.map((item, index) => (
      //   <div onClick={() => onHandlerClickItem(item, index)}>
      //     {index} {item.title}
      //   </div>
      // ));
    };

    const readerCustomResultList = () => {
      return computedRows.value.map((item, index) => (
        <div onClick={() => onHandlerClickItem(item, index)}>
          {slots.default?.(item)}
        </div>
      ));
    };

    const readerPullToRefreshDefaultSlot = () => {
      return slots.default && 'custom' == mappingProps.itemTemplate
        ? readerCustomResultList()
        : readerResultList();
    };

    const readerPullToRefresh = () => {
      return (
        <TPullToRefresh onRefresh={refresh} disable={!mappingProps.pullRefresh}>
          <TInfiniteScroll
            disable={mappingProps.finished}
            ref={refInfiniteScroll}
            onLoad={onLoad}
            scroll-target={refScrollTargetId.value}
            offset={250}
            style='margin-left: 16px;margin-right: 16px;background-color: #fff;'>
            {{
              default: readerPullToRefreshDefaultSlot,
              loading() {
                return (
                  <div class='row justify-center q-my-md'>
                    <TSpinnerDots color='primary' size='40px' />
                  </div>
                );
              },
            }}
          </TInfiniteScroll>
        </TPullToRefresh>
      );
    };

    const defEmpty = () => {
      // return <Empty image='search'></Empty>;
      return (
        <NoDataPlaceholder
          text={$q.lang.dataGrid?.emptyText}
        ></NoDataPlaceholder>
      );
    };

    const readerError = empty => {
      return props.error ? (
        // <Empty image='error' description={mappingProps.errorText} />
        <NoDataPlaceholder text={mappingProps.errorText}></NoDataPlaceholder>
      ) : (
        empty
      );
    };

    const readerEmptySolt = () => {
      return props.loading ? (
        <div style='visibility: hidden;'>
          <Loading showing={props.loading} />
        </div>
      ) : props.error ? (
        // <Empty image='error' description={mappingProps.errorText} />
        <NoDataPlaceholder text={mappingProps.errorText}></NoDataPlaceholder>
      ) : (
        readerError(slots.empty())
      );
    };

    const readerEmptyDefault = () => {
      return props.loading ? (
        <div style='visibility: hidden;'>
          <Loading showing={props.loading} />
        </div>
      ) : (
        readerError(defEmpty())
      );
    };

    const readerEmpty = () => {
      return slots.empty ? readerEmptySolt() : readerEmptyDefault();
    };

    const updateScrollTarget = () => {
      refInfiniteScroll.value?.updateScrollTarget();
    };

    const onResize = () => {
      updateScrollTarget();
    };

    const readerList = () => {
      return (
        <TCardSection class='q-pa-none' style="height:100%">
          <TResizeObserver onResize={onResize} />
          {computedRows.value?.length ? readerPullToRefresh() : readerEmpty()}
        </TCardSection>
      );
    };

    const readerHistory = () => {
      return (
        <History
          historyArray={historyArray}
          onClick={history => {
            searchValue.value = history.title;
            publicMethod.refresh();
          }}
          onRemove={index => {
            historyArray.splice(index, 1);
            emitUpdateHistory(historyArray);
          }}
          onClear={() => {
            historyArray.length = 0;
            emitUpdateHistory(historyArray);
          }}
        ></History>
      );
    };
    const readerHistoryMain = () => {
      return mappingProps.history && historyArray.length > 0 && readerHistory();
    };

    const readerSpinner = () => (
      <div class='row justify-center q-my-md'>
        <t-spinner-dots color='primary' size='40px' />
      </div>
    );

    const readerTotalCountInfo = () => {
      return (
        isQueryFlag.value && (
          <TCardSection
            class='q-pa-none popup-search_searchbar__totalCountBar'>
              <span innerHTML={$q.lang.popupSearch.totalCount.replace('{totalCount}',"<span style='margin: auto 3px; color:var(--t-color)'>"+mappingProps.totalCount+"</span>")}></span>
          </TCardSection>
        )
      );
    };

    const leftSlot = () => {
      return (
        <TButton
          flat
          round
          dense
          class='q-pl-md left-icon-fontsize'
          icon='arrow_back_ios'
          v-close-popup
          // onClick={() => setShowPopup(false)}
        />
      );
    };

    const cancelSlot = () => {
      return (
        <TButton
          flat
          dense
          label={$q.lang.popupSearch.btnCancel}
          style={{ minWidth: 'auto', padding: '0px', color:'var(--t-color)' }}
          // v-close-popup
          onClick={() => setShowPopup(false)}
        />
      );
    };

    const actionSlot = () => {
      return (
        <TButton
          flat
          dense
          label={$q.lang.popupSearch.btnSearch}
          style={{ minWidth: 'auto' }}
          onClick={() => {
            onHandlerSearch();
          }}
        />
      );
    };

    const readerPopupSearchBar = () => {
      return (
        <TCardSection class={['q-px-none q-py-sm popup-search_container', props.compact && 'popup' ]}>
          <div class='row' style='column-gap: 10px;'>
            {/* <div class='col-auto'>{leftSlot()}</div> */}
            <div class='col'>
              <QInput
                ref={refSearch}
                class='popup-search_searchbar'
                // bg-color='#F0F2F5'
                // dense
                // filled
                type='search'
                standout
                borderless
                debounce='500'
                outlined={false}
                bottom-slots
                placeholder={mappingProps.placeholder}
                v-model={searchValue.value}
                clearable
                onUpdate:modelValue={() => onHandlerSearch(false)}
                onKeydown={e => {
                  if (13 == e.keyCode) {
                    onHandlerSearch(true);
                    refSearch?.value?.blur();
                  }
                }}
                onFocus={() => (isHistoryView.value = true)}
                // onBlur={() =>
                //   setTimeout(() => {
                //     isHistoryView.value = false;
                //   }, 300)
                // }
                onClear={() => (isHistoryView.value = false)}
              >
                {{
                  // before: leftSlot,
                  prepend: () => <TIcon name='icon-fassearch01' />,
                  // after: actionSlot,
                }}
              </QInput>
            </div>
            <div class='col-auto row self-center'>{cancelSlot()}</div>
          </div>
        </TCardSection>
      );
    };

    const readerEmpty2 = () => {
      return (
        !(
          isHistoryView.value &&
          mappingProps.history &&
          historyArray.length > 0
        ) && (
          <>
            <div style='display: flex;place-content: center;width: 100%;justify-content: flex-start;'>
              <TCardSection class='q-pa-none popup-search_searchbar__totalCountBar'>
                <span>&nbsp;</span>
              </TCardSection>
            </div>
            {defEmpty()}
          </>
        )
      );
    };

    const readerPopup = () => {
      return (
        <TDialog
          persistent-
          maximized
          forceTouchHide={true}
          v-model={
            showPopup.value
          } /** t层 组件此刻不兼容这个模式，留着是为了后续组件支持 */
          v-model:show={showPopup.value}
          transition-show='slide-left'
          transition-hide='slide-right'
        >
          <TCard>
            <div class='column' style='height: 100%'>
              <div class='col-auto'>
                {readerPopupSearchBar()}
                {isHistoryView.value
                  ? readerHistoryMain()
                  : readerTotalCountInfo()}
              </div>
              {/* {refreshing.value ? readerSpinner() : readerContent()} */}
              {props.loading ? readerSpinner() : readerContent()}
            </div>
          </TCard>
        </TDialog>
      );
    };

    const readerDesign = () => {
      const slot = slots[mappingProps.itemTemplateCustomSlot];

      return (
        <TDialog
          maximized
          v-model={
            mappingProps.itemTemplateCustom
          } /** t层 组件此刻不兼容这个模式，留着是为了后续组件支持 */
          v-model:show={mappingProps.itemTemplateCustom}
          transition-show='slide-left'
          transition-hide='slide-right'
        >
          <TCard>
            <div class='column' style='height: 100%'>
              <div class='col'>{readerPopupSearchBar()}</div>
              <div class='col' style='overflow: auto; height: 100%'>
                <div class='designContainer'>{slot && slot()}</div>
              </div>
              <div
                class='col-auto'
                onClick={() => {
                  mappingProps.itemTemplateCustom = false;
                }}
                style='cursor: pointer;position: absolute;bottom: 0px;right: 0px;margin: 20px;'
              >
                退出设计
              </div>
            </div>
          </TCard>
        </TDialog>
      );
    };


    const readerContent = () => {
      return false == isHistoryView.value ? (
        <div
          class='col refScrollTarget'
          id='refScrollTargetId'
          ref={refScrollTargetId}
          onClick={() => {
            isHistoryView.value = false;
          }}
        >
          {!isHistoryView.value && isQueryFlag.value ? (
            readerList()
          ) : (
            <div
              class='col'
              style='height:100%; flex-direction: column;background-color: #F9F9FB;display: flex;align-content: center;justify-content: center;align-items: center;'
            >
              {readerEmpty2()}
            </div>
          )}
        </div>
      ) : (
        <div
          onClick={() =>
            setTimeout(() => {
              isHistoryView.value = false;
            }, 300)
          }
          class='col'
          style='flex-direction: column;background-color: #F9F9FB;display: flex;align-content: center;justify-content: center;align-items: center;'
        >
          {readerEmpty2()}
        </div>
      );
    };

    return () => {
      return (
        <div class={Style.main}>
          {mappingProps.showSearchBar ? renderSearch() : renderSearchIcon()}
          {readerPopup()}
          {inDesign && 'custom' == mappingProps.itemTemplate && readerDesign()}
        </div>
      );
    };
  },
});
